$(function ()
{
    var Request = new Object();
    Request = getUrlRequest();

    var reformNo = "";
    var tableNo = "";
    var orderNo = Request["orderNo"];

    //查询此订单号整改单的数量
    $.ajax(
    {
        url : '../../api/nj_getReformCountByOrderNo',
        data : 'orderNo=' + orderNo,
        type : 'GET',
        dataType : 'json',
        timeout : 6000,
        success : function (data)
        {
            if (parseInt(data) < 10)
            {
                reformNo = orderNo + 'ZG0' + (parseInt(data) + 1).toString();
            }
            else
            {
                reformNo = orderNo + 'ZG' + (parseInt(data) + 1).toString();
            }
            $('#reformNo').textbox('setValue', reformNo);
        }
    }
    )

    //设置表号
    $('#tableNo').textbox('setValue', "HK/CW050405F02");

    /*根据订单编号初始化相关信息*/
   //根据订单编码查询订单信息
    $.ajax(
    {
        url : '../../api/nj_getOrderData?orderNo='+orderNo+'&status=0', //返回订单信息
        type : 'GET',
        dataType : 'json',
        timeout : 5000,
        cache : false,
        //error : erryFunction, //错误执行方法
        success : successFunction //成功执行方法

    }
    );

    function successFunction(responseData)
    {
       //为订单信息赋值
       //产品型号编码
       $('#workOperationoutmainitemcode').textbox('setValue',responseData.rows[0].workOperationoutmainitemcode);
       //订单类型
       $('#workuserBaoxiao').textbox('setValue',responseData.rows[0].workuserBaoxiao);
       //计划时间
       $('#workuserDay').datetimebox('setValue',responseData.rows[0].workuserDay);
       //订单编码
       $('#orderNo').textbox('setValue',responseData.rows[0].workuserMordercode);
       //线体名称
       $('#workuserLinename').textbox('setValue',responseData.rows[0].workuserLinename);
       //产品型号名称
       $('#productdescription').textbox('setValue',responseData.rows[0].productdescription);
    }




    //下方datagrid的相关配置
    var off = 1; //单击时开启行编辑  0为关闭
    var datagrid;
    var editRow = undefined;
    var rowEditor = undefined;

    datagrid = $("#OrderTestOffGrade").datagrid(
        {

            url : "../../api/getOrderTestOffGradeByReformNo?reformNo=" + reformNo, //加载的URL
            method : 'get',
            isField : "id",
            nowrap : false,
            singleSelect : true,
            pagination : false, //显示分页
            pageSize : 5, //分页大小
            pageList : [5, 10, 15, 20], //每页的个数
            beforePageText : '第', //页数文本框前显示的汉字
            afterPageText : '页    共 {pages} 页',
            displayMsg : '当前显示 {from} - {to} 条记录   共 {total} 条记录',
            fit : false, //自动补全
            fitColumns : true,
            height : 300,
            rownumbers : true,
            title : "一、测试不合格描述：",
            columns : [[//每个列具体内容
                    {
                        field : 'reformNo',
                        title : '整改单编号',
                        width : 170,

                    },
                    {
                        field : 'orderTestItemID',
                        title : '不合格项目编号',
                        width : 60,
                        hidden : true,
                        editor :
                        {
                            type : 'textbox',
                            options :
                            {
                                readonly : "readonly",
                            }
                        }
                    },
                    {
                        field : 'orderTestItemName',
                        title : '不合格项目',
                        width : 120,
                        editor :
                        {
                            type : 'combobox',
                            options :
                            {
                                required : true,
                                valueField : 'name',
                                textField : 'name',
                                method : "get",
                                url : '../../api/getOrderTestItemByOrderNo?orderNo=' + orderNo,
                                onSelect : function (rec)
                                {
                                    /*$('#OrderTestOffGrade').datagrid('updateRow', {index: 0, row: {orderTestItemID : rec.testitemid,
                                    orderTestItemName:rec.name,
                                    }});*/
                                    /*var row=datagrid.datagrid('getSelected');
                                    var index = datagrid.datagrid('getRowIndex');*/

                                    var editors = $('#OrderTestOffGrade').datagrid('getEditors', 0);
                                    var orderTestItemDescription = editors[2];
                                    orderTestItemDescription.target.val(rec.standarddemand);
                                    var orderTestItemID = editors[0];
                                    $(orderTestItemID.target).textbox('setValue', rec.testitemid);
                                    /*$(amountEditor.target).textarea('setValue','cost');*/
                                    /*$('#OrderTestOffGrade').datagrid('beginEdit',0);*/

                                }
                            }
                        }
                    },
                    {
                        field : 'orderTestItemDescription',
                        title : '标准要求',
                        width : 200,
                        editor :
                        {
                            type : 'textarea',
                            id : '11',
                            height : 100,
                            options :
                            {

                                /*multiline:true,*/
                            }
                        }
                    },
                    {
                        field : 'orderTestItemResult',
                        title : '判定结论',
                        width : 50,
                        editor :
                        {
                            type : 'combobox',
                            options :
                            {
                                valueField : 'value',
                                textField : 'orderTestItemResult',
                                required : true,
                                data : [
                                    {
                                        orderTestItemResult : 'F',
                                        value : 'F'
                                    },
                                    {
                                        orderTestItemResult : 'E',
                                        value : 'E'
                                    }
                                ],
                                required : true
                            }
                        }
                    },
                    {
                        field : 'appearanceCodeSelect',
                        title : '现象码选择',
                        width : 60,
                        formatter : function (value, row, index)
                        {
                            console.log('row.id:' + row.id);
                            console.log('index:' + index);
                            console.log('value:' + value);
                            return '<a id="xxm" href="javascript:void(0)" class="easyui-linkbutton" onclick="geta(' + index + ');">选择</a>';
                        }
                    },
                    {
                        field : 'appearanceCode',
                        title : '现象码',
                        width : 40,
                        editor :
                        {
                            type : 'textbox',
                            options :
                            {
                                readonly : "readonly",
                            }
                        }
                    },
                    {
                        field : 'appearanceName',
                        title : '现象名称',
                        width : 60,
                        editor :
                        {
                            type : 'textbox',
                            options :
                            {
                                readonly : "readonly",
                            }
                        }
                    },
                    {
                        field : 'appearanceDiscribe',
                        title : '现象描述',
                        width : 200,
                        editor :
                        {
                            type : 'textarea',
                            id : '11',
                            height : 100,
                            options : {}
                        }
                    },
                    {
                        field : 'addUser',
                        title : '添加人',
                        width : 40,
                    },
                ]],
            toolbar : [//工具条
                {
                    text : "增加",
                    iconCls : "icon-add",
                    handler : function ()
                    { //回调函数
                        /* if(sampleinfono.length != 0){*/
                        if (rowEditor != undefined)
                        {
                            datagrid.datagrid('endEdit', rowEditor);
                            datagrid.datagrid('acceptChanges');
                            rowEditor = undefined;
                        }
                        if (rowEditor == undefined)
                        {
                            datagrid.datagrid('insertRow',
                            { //如果处于未被点击状态，在第一行开启编辑
                                index : 0,
                                row :
                                {
                                    'addUser' : realname,
                                    'reformNo' : document.getElementById("reformNo").value,
                                }

                            }
                            );
                            rowEditor = 0;
                            datagrid.datagrid('beginEdit', rowEditor); //没有这行，即使开启了也不编辑
                        }
                        else
                        {}
                        /*  }else{
                        $.messager.alert('操作提示',"请先保存样品信息！");
                        }*/

                    }
                }, '-',
                {
                    text : "修改",
                    iconCls : "icon-edit",
                    handler : function ()
                    {
                        var rows = datagrid.datagrid('getSelections');
                        if (rows.length == 1)
                        {
                            if (rowEditor == undefined)
                            {
                                var index = datagrid.datagrid('getRowIndex', rows[0]);
                                rowEditor = index;
                                datagrid.datagrid('unselectAll');
                                datagrid.datagrid('beginEdit', index);

                            }
                        }
                    }
                }, '-',
                {
                    text : "删除",
                    iconCls : "icon-remove",
                    handler : function ()
                    {
                        var rows = datagrid.datagrid('getSelections');

                        if (rows.length <= 0)
                        {
                            $.messager.alert('警告', '您没有选择', 'error');
                        }
                        else if (rows.length > 1)
                        {
                            $.messager.alert('警告', '不支持批量删除', 'error');
                        }
                        else
                        {
                            $.messager.confirm('确定', '您确定要删除吗', function (t)
                            {
                                if (t)
                                {
                                    var row = rows[0];
                                    var index = datagrid.datagrid('getRowIndex', row);
                                    datagrid.datagrid('deleteRow', index);
                                }
                            }
                            )
                        }
                    }
                }, '-',
                {
                    text : "保存",
                    iconCls : "icon-save",
                    handler : function ()
                    {

                        datagrid.datagrid('endEdit', rowEditor);
                        rowEditor = undefined;
                    }
                }, '-',
                {
                    text : "取消编辑",
                    iconCls : "icon-redo",
                    handler : function ()
                    {
                        rowEditor = undefined;
                        datagrid.datagrid('rejectChanges')
                    }
                }, '-'
            ],
            onAfterEdit : function (rowIndex, rowData, changes)
            {
                var inserted = datagrid.datagrid('getChanges', 'inserted');
                var updated = datagrid.datagrid('getChanges', 'updated');
                if (inserted.length < 1 && updated.length < 1)
                {
                    editRow = undefined;
                    datagrid.datagrid('unselectAll');
                    return;
                }

                var url = '';
                /*if (updated.length > 0) {
                url = 'api/updateSamTecParameters';
                }
                if (inserted.length > 0) {
                url = 'api/InsertSamTecParameters';
                }*/

                $.ajax(
                {
                    url : url,
                    data : rowData,
                    dataType : 'json',
                    success : function (r)
                    {
                        if (r == 1)
                        {
                            datagrid.datagrid('acceptChanges');
                            $.messager.show(
                            {
                                msg : r.msg,
                                title : '成功'
                            }
                            );
                            editRow = undefined;
                            datagrid.datagrid('reload');
                        }
                        else
                        {
                            /*datagrid.datagrid('rejectChanges');*/
                            datagrid.datagrid('beginEdit', editRow);
                            $.messager.alert('错误', r.msg, 'error');
                        }
                        datagrid.datagrid('unselectAll');
                    }
                }
                );
            },
            onDblClickCell : function (rowIndex, field, value)
            {
                if (rowEditor == undefined && off == 1)
                {
                    datagrid.datagrid('beginEdit', rowIndex);
                    rowEditor = rowIndex;
                }

            }
        }
        );

    //保存整改单
    $('#saveReportForm').bind('submit', function ()
    {

        var rows = $("#OrderTestOffGrade").datagrid("getRows");
        if (rows.length > 0)
        {
            ajaxSubmit(this, function (data)
            {

                datagrid.datagrid('endEdit', rowEditor);
                rowEditor = undefined;
                saveOrderTestOffGrade();
                saveOrderTracksRecord();
                $(".datagrid-toolbar").hide(); //隐藏toolbar工具栏
                off = 0; //关闭datagrid的onDblClickCell单击编辑功能

                //portal待办
                var isss = $("#issuedUserNo").val();
                var userid123 = $("#oderBailorNo").val();
                var title123 = "接收整改单";
                var digest123 = "有待接收的整改单";
                var initiator123 = isss;
                var fromuserid123 = isss;
                var taskviewurl123 = firstURL + "/menu/SubmitReports/submitreport?testnum=" + orderNo;
                var sampleno123 = "";
                var orderno123 = orderNo;
                var recorderno123 = $("#reformNo").val();
                $.ajax(
                {
                    type : "get",
                    dataType : "json",
                    url : "../../api/BeginPoratlTask",
                    data :
                    {
                        userid : userid123,
                        title : title123,
                        digest : digest123,
                        initiator : initiator123,
                        fromuserid : fromuserid123,
                        taskviewurl : taskviewurl123,
                        sampleno : sampleno123,
                        orderno : orderno123,
                        recorderno : recorderno123
                    },
                    success : function ()
                    {
                        console.log("portal待办成功！");
                    },
                    error : function (e)
                    {
                        console.log("portal待办失败！");
                    }
                }
                );

                //将整改单的状态改为--“18待接收整改单”
                $.ajax(
                {
                    url : "../../api/updateStatusOfOrderTestReform",
                    type : "GET",
                    data :
                    {
                        status : "18",
                        reformNo : document.getElementById("reformNo").value
                    },
                    dataType : "json",
                    success : function ()
                    {
                        //$.messager.alert("操作提示", "测试填写整改单完成并提交成功！","info");
                        // $.messager.alert('操作提示',"标准项保存成功！");
                        //显示已经选定的标准项信息

                        /*$.messager.confirm("操作提示", "生成整改单成功！是否跳转到订单进度查询界面", function (r) {
                        if (r) {
                        window.location.href="../../menu/OrderManage/OrderProgressSearch";
                        }
                        });*/
                        window.location.href = "../../menu/OrderManage/OrderProgressSearch";
                    },
                    error : function (e)
                    {
                        //$.messager.alert('操作提示',"错误：" + e);
                    }
                }
                );
            }
            );
        }
        else
        {
            $.messager.alert("操作提示", "测试不合格信息未描述，请填写！", "info");
        }
        return false;
    }
    );

    var dgIndex;
    var re = undefined;

    //现象码选择的搜索按钮事件
    $('#searchPerson').click(function ()
    {

        var aps = $('#appearanceSelect').val();
        var prd = $('#productSelect').val();
        //全都查询出来
        $.ajax(
        {
            url : "../../api/getAppearanceInfoByTypeCode?appearancecode=" + aps + "&producttype=" + prd + "&page=1&rows=999",
            dataType : "json",
            type : "GET",
            success : function (datas)
            {

                $('#showAppearanceTable').datagrid('loadData',
                {
                    total : 0,
                    rows : []
                }
                );
                $('#showAppearanceTable').datagrid('loadData', datas);

            },
            error : function (e)
            {
                $.messager.alert('操作提示', "操作失败失败，请稍后再试");
            }
        }
        );
    }
    );

    //点击编制人面板的【确定按钮】
    $('#btnPersonSelect').click(function ()
    {

        var rows = $('#showAppearanceTable').datagrid('getSelections');
        // var sno="";
        console.log('rows[0].appearancecode' + rows[0].appearancecode);
        console.log('dgIndex:' + dgIndex);

        var editors = $('#OrderTestOffGrade').datagrid('getEditors', dgIndex);
        var e4 = editors[4];
        var e5 = editors[5];
        $(e4.target).textbox('setValue', rows[0].appearancecode);
        $(e5.target).textbox('setValue', rows[0].appearancename);

        $('#selectAppearanceCode').window('close');
    }
    );

    //点击编制人面板的【取消按钮】
    $('#btnPersonCancel').click(function ()
    {

        $('#selectAppearanceCode').window('close');
    }
    );
}
);

//将form转为AJAX提交
function ajaxSubmit(frm, fn)
{
    var dataPara = getFormJson(frm);
    $.ajax(
    {
        url : frm.action,
        type : frm.method,
        data : dataPara,
        success : fn
    }
    );
}

//将form中的值转换为键值对。
function getFormJson(frm)
{
    var o = {};
    var a = $(frm).serializeArray();
    $.each(a, function ()
    {
        if (o[this.name] !== undefined)
        {
            if (!o[this.name].push)
            {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        }
        else
        {
            o[this.name] = this.value || '';
        }
    }
    );

    return o;
}

/*保存datagrid测试项目不合格描述信息*/
function saveOrderTestOffGrade()
{
    var exitRows = $('#OrderTestOffGrade').datagrid('getRows');
    var reformNoList = document.getElementById("reformNo").value;
    var orderTestItemIDList = "";
    var orderTestItemNameList = "";
    var orderTestItemDescriptionList = "";
    var orderTestItemResultList = "";
    var reasonAnalysisList = "";
    var addTimeList = document.getElementById("issuedDate").value.toString();
    var addUserList = realname;

    //刘天宇增加
    var appearanceCodeList = "";
    var appearanceNameList = "";
    var appearanceDiscribeList = "";
    if (exitRows.length < 0)
    {
        $.messager.alert('操作提示', '请填写测试不合格描述');
    }
    else
    {
        for (var i = 0; i < exitRows.length; i++)
        {
            //字符串组合，**,**,
            orderTestItemIDList = orderTestItemIDList + exitRows[i].orderTestItemID + "@";
            orderTestItemNameList = orderTestItemNameList + exitRows[i].orderTestItemName + "@";
            orderTestItemDescriptionList = orderTestItemDescriptionList + exitRows[i].orderTestItemDescription + "@";
            if (exitRows[i].orderTestItemResult == "")
            {
                exitRows[i].orderTestItemResult = " ";
            }
            orderTestItemResultList = orderTestItemResultList + exitRows[i].orderTestItemResult + ",";

            //lty增加
            appearanceCodeList = appearanceCodeList + exitRows[i].appearanceCode + "@";
            appearanceNameList = appearanceNameList + exitRows[i].appearanceName + "@";
            if (exitRows[i].appearanceDiscribe == "")
            {
                exitRows[i].appearanceDiscribe = " ";
            }
            appearanceDiscribeList = appearanceDiscribeList + exitRows[i].appearanceDiscribe + "@";
        }
    }
    /*截取*/
    orderTestItemIDList = orderTestItemIDList.substring(0, orderTestItemIDList.length - 1);
    orderTestItemNameList = orderTestItemNameList.substring(0, orderTestItemNameList.length - 1);
    orderTestItemDescriptionList = orderTestItemDescriptionList.substring(0, orderTestItemDescriptionList.length - 1);
    orderTestItemResultList = orderTestItemResultList.substring(0, orderTestItemResultList.length - 1);

    //lty增加
    appearanceCodeList = appearanceCodeList.substring(0, appearanceCodeList.length - 1);
    appearanceNameList = appearanceNameList.substring(0, appearanceNameList.length - 1);
    appearanceDiscribeList = appearanceDiscribeList.substring(0, appearanceDiscribeList.length - 1);

    //插入不合格描述
    $.ajax(
    {
        url : "../../api/insertOrderTestOffGrade",
        type : "GET",
        data :
        {
            reformNo : reformNoList,
            orderTestItemID : orderTestItemIDList,
            orderTestItemName : orderTestItemNameList,
            orderTestItemDescription : orderTestItemDescriptionList,
            orderTestItemResult : orderTestItemResultList,
            reasonAnalysis : reasonAnalysisList,
            addTime : addTimeList,
            addUser : addUserList,
            //lty增加
            appearanceCode : appearanceCodeList,
            appearanceName : appearanceNameList,
            appearanceDiscribe : appearanceDiscribeList
        },
        dataType : "json",
        success : function ()
        {
            // $.messager.alert('操作提示',"标准项保存成功！");
            //显示已经选定的标准项信息
        },
        error : function (e)
        {
            $.messager.alert('操作提示', "错误：" + e);
        }
    }
    );
}
function getNowFormatDate()
{
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9)
    {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9)
    {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
         + " " + date.getHours() + seperator2 + date.getMinutes()
         + seperator2 + date.getSeconds();
    return currentdate;
}
//保存跟踪单
function saveOrderTracksRecord()
{
    var operationtime = getNowFormatDate();
    $.ajax(
    {
        url : "../../api/saveOrderTracksRecord",
        type : "GET",
        data :
        {
            orderno : orderNo,
            operationtime : operationtime,
            userno : userno,
            operation : '整改管理：测试经理填写整改单',
            remarks : '填写整改单基本信息、测试不合格描述等信息。',
            addtime : operationtime,
            adduser : realname,
            userrole : rolename,
            username : realname
        },
        dataType : "json",
        success : function ()
        {
            //$.messager.alert("操作提示", "跟踪的保存成功！","info");
            // $.messager.alert('操作提示',"标准项保存成功！");
            //显示已经选定的标准项信息

        },
        error : function (e)
        {
            //$.messager.alert('操作提示',"错误：" + e);
        }
    }
    );
}

/*提交按钮响应函数*/
function commit()
{
    $('#saveReportForm').submit();
    $(".datagrid-toolbar").hide(); //隐藏toolbar工具栏
    off = 0; //关闭datagrid的onDblClickCell单击编辑功能
    saveOrderTracksRecord();
    //将整改单的状态改为--“18待接收整改单”
    $.ajax(
    {
        url : "../../api/updateStatusOfOrderTestReform",
        type : "GET",
        data :
        {
            status : "18",
            reformNo : document.getElementById("reformNo").value
        },
        dataType : "json",
        success : function ()
        {
            $.messager.alert("操作提示", "测试填写整改单完成并提交成功！", "info");
            // $.messager.alert('操作提示',"标准项保存成功！");
            //显示已经选定的标准项信息
            window.location.href = "../../menu/OrderManage/OrderProgressSearch";
        },
        error : function (e)
        {
            //$.messager.alert('操作提示',"错误：" + e);
        }
    }
    );
}

//选择现象码按钮功能
function geta(index)
{
    dgIndex = index;
    $('#OrderTestOffGrade').datagrid('beginEdit', dgIndex);
    rowEditor = dgIndex;
    $('#selectAppearanceCode').window('open').window('move',
    {
        left : 350,
        top : 200
    }
    );
};
